﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Security.Cryptography;
using DuplicateFileFinder.Infrastructure;
using DuplicateFileFinder.Model;
using System.Text;

namespace DuplicateFileFinder.Business
{
    public class Hasher
    {
        #region Fields

        private long count;
        private long dupCount;
        private SearchResultQueue inputQueue;
        private Dictionary<string, List<FileProperty>> hashResult;

        #endregion

        #region Public

        public Hasher()
        {
            inputQueue = SearchResultQueue.Instance;
        }

        public void Start()
        {
            hashResult = new Dictionary<string, List<FileProperty>>();
            PerformAction();
        }

        private void PerformAction()
        {
            String currFile;

            if (inputQueue.Count == 0)
                ThreadSynchronizer.Wait(5000);

            while (inputQueue.Count != 0)
            {
                currFile = inputQueue.DeQueue();
               // UIManager.Instance.UpdateStatus(currFile);
                count++;

                FileStream fsin = null;
                MD5 md5 = null;

                try
                {
                    md5 = new MD5CryptoServiceProvider();
                    fsin = new FileStream(currFile, FileMode.Open);
                    md5.ComputeHash(fsin);
                }
                catch (Exception ex)
                {
                    if (fsin != null)
                    {
                        fsin.Close();
                        fsin.Dispose();
                    }
                    if (inputQueue.Count == 0)
                        ThreadSynchronizer.Wait(5000);

                    continue;
                }

                string hashString = Encoding.UTF8.GetString(md5.Hash);

                UIManager.Instance.UpdateStatus(inputQueue.Count.ToString());
            }

            UIManager.Instance.UpdateStatus("Done");
        }

        #endregion
    }
}
